<?php

namespace app\api\services;

use app\admin\model\Technician;
use app\api\model\FareOrder;
use app\api\model\Order;
use app\api\model\TechnicianMoneyLog;
use ba\Exception;
use think\facade\Db;
use think\facade\Log;

class OrderService
{
    protected static string|null $out_trade_no = null;
    protected static string|null $transaction_id = null;
    protected static string|null $attach = null;
    protected static string|null $payer_total = null;
    protected static string|null $success_time = null;

    public function __construct ($out_trade_no, $transaction_id, $attach, $payer_total, $success_time)
    {
        self::$out_trade_no = $out_trade_no;
        self::$transaction_id = $transaction_id;
        self::$attach = $attach;
        self::$payer_total = $payer_total;
        self::$success_time = $success_time;
    }

    /**
     * 订单和加钟回调
     * @return bool|Exception
     * @throws \think\db\exception\DbException
     */
    public function orderPayCallback (): bool|Exception
    {

        $orderModel = new Order();
        $orderInfo = $orderModel->where('order_sn', self::$out_trade_no)->find();
        if (empty($orderInfo)) {
            throw new Exception('orderPayCallback 订单不存在 order_sn：' . self::$out_trade_no . ' 支付交易号 ' . self::$transaction_id);
        }
        $orderInfo->pay_way = 'wechat'; //支付方式
        if ($orderInfo->type == 1) {
            $orderInfo->order_state = 'Received'; //订单状态 已接单
        } else {
            $orderInfo->order_state = 'Start'; //订单状态 已支付
        }
        $orderInfo->payment_order_sn = self::$transaction_id; //支付订单号
        $orderInfo->service_reality_price = self::$payer_total; //实际支付金额
        $orderInfo->payment_time = self::$success_time; //支付成功时间
        $orderInfo->save();


        #写入时间预约
        Db::name('order_reservation')->insert([
            'user_id'          => $orderInfo->user_id,
            'technician_id'    => $orderInfo->technician_id,
            'reservation_time' => $orderInfo->service_start_time,
            'order_sn'         => $orderInfo->order_sn,
            'create_time'      => date('Y-m-d H:i:s', time()),
        ]);

        #记录订单状态
        setOrderStateLog($orderInfo->id, 'Paid');
        setOrderStateLog($orderInfo->id, 'Received');

        #给技师发送短信
        try {
            $username = \app\admin\model\Technician::where('technician_id', $orderInfo->technician_id)->value('username');
            sms_send($orderInfo->technician_tel, 'technician_order', ['account' => $username]);
        } catch (\Exception $e) {
            Log::error('支付回调-技师接单短信发送失败' . $e->getMessage());
        }
        return true;
    }

    /**
     * 充值回调
     * @return bool|Exception
     */
    public function rechargePayCallback (): bool|Exception
    {
        $orderModel = new \app\admin\model\stored\value\Order();
        $orderInfo = $orderModel->where('order_sn', self::$out_trade_no)->find();
        if (empty($orderInfo)) {
            throw new Exception('rechargePayCallback 订单不存在 order_sn：' . self::$out_trade_no . ' 支付交易号 ' . self::$transaction_id);
        }
        $orderInfo->pay_type = 'wechat'; //支付方式
        $orderInfo->state = 2; //订单状态 已支付
        $orderInfo->pay_sn = self::$transaction_id; //支付订单号
        $orderInfo->reality_pay_amount = self::$payer_total; //实际支付金额
        $orderInfo->pay_time = self::$success_time; //支付成功时间
        $orderInfo->save();

        #加入余额变动表
        $userMoneyLog = new \app\admin\model\UserMoneyLog();
        $userMoneyLogInfo = $userMoneyLog
            ->where('user_id', $orderInfo->user_id)
            ->order('create_time', 'desc')
            ->find();
        if (!$userMoneyLogInfo) {
            $before = 0;
        } else {
            $before = $userMoneyLogInfo->after;
        }
        $userMoneyLog->money = $orderInfo->received_amount; //实际到账
        $userMoneyLog->user_id = $orderInfo->user_id;
        $after = bcadd($before, $orderInfo->received_amount, 2);
        $userMoneyLog->after = $after;
        $userMoneyLog->memo = '充值' . self::$payer_total . '元 实际到账 ' . $orderInfo->received_amount . '元';
        $userMoneyLog->create_time = date('Y-m-d H:i:s');
        $userMoneyLog->type = 1;
        $userMoneyLog->save();
        #修改用户表余额
        $userModel = new \app\admin\model\User();
        $userInfo = $userModel->where('id', $orderInfo->user_id)->find();
        $userInfo->money = bcadd($userInfo->money, $orderInfo->received_amount, 2);
        $userInfo->save();
        return true;
    }

    /**
     * 打车费回调
     * @return bool|Exception
     */
    public function farePayCallback (): bool|Exception
    {

        $orderModel = new FareOrder();
        $orderInfo = $orderModel->where('fare_order_sn', self::$out_trade_no)->find();
        if (empty($orderInfo)) {
            throw new Exception('farePayCallback 订单不存在 order_sn：' . self::$out_trade_no . ' 支付交易号 ' . self::$transaction_id);
        }
        if ($orderInfo->fare_state != 'ToBePaid') {
            throw new Exception('farePayCallback 订单状态不正确 order_sn：' . self::$out_trade_no . ' 支付交易号 ' . self::$transaction_id);
        }

        $orderInfo->fare_pay_state = 'wechat'; //支付方式
        $orderInfo->fare_state = 'Paid'; //订单状态 已支付
        $orderInfo->fare_technician_id = self::$transaction_id; //支付订单号
        $orderInfo->fare_pay_price = self::$payer_total; //实际支付金额
        $orderInfo->fare_pay_time = self::$success_time; //支付成功时间

        #加入技师余额变动表
        $TechnicianMoneyLog = new TechnicianMoneyLog();
        $technicianMoneyLogInfo = $TechnicianMoneyLog->where('technician_id', $orderInfo->technician_id)->order('create_time', 'desc')->find();
        if (!$technicianMoneyLogInfo) {
            $TechnicianMoneyLog->before = 0;
        } else {
            $TechnicianMoneyLog->before = $technicianMoneyLogInfo->after;
        }
        $TechnicianMoneyLog->money = $orderInfo->fare_pay_price;
        $TechnicianMoneyLog->technician_id = $orderInfo->technician_id;
        $TechnicianMoneyLog->after = bcadd($TechnicianMoneyLog->before, $orderInfo->fare_price, 2);
        $TechnicianMoneyLog->memo = '车费附加订单' . $orderInfo->fare_order_sn;
        $TechnicianMoneyLog->create_time = date('Y-m-d H:i:s', time());
        $TechnicianMoneyLog->type = 2;//1正常收入 2 车费  3 提现 4 手动增加余额 5手动减少余额
        $TechnicianMoneyLog->order_id = $orderInfo->fare_id;

        #技师余额修改
        $info = Technician::where('technician_id', $orderInfo->technician_id)->find();
        $info->money = bcadd($info->money, $orderInfo->fare_price, 2);
        $info->save();
        $orderInfo->save();
        $TechnicianMoneyLog->save();

        return true;
    }


}